package com.yyk.yiliao.ui.home.activity;


import android.os.Bundle;
import android.os.Handler;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.RatingBar;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.StoreNear_Info;
import com.yyk.yiliao.widget.EndLessOnScrollListener;
import com.yyk.yiliao.widget.diver.CustomDecoration;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 附近药店
 */

public class Nearby_Activity extends BaseActivity {

    @BindView(R.id.mNearby_rc)
    RecyclerView mNearbyRc;

    private int pageIndex = 1; //默认等于1
    //附近药店集合
    List<StoreNear_Info.DataBean> nearList = new ArrayList<>();
    private BaseRecyclerAdapter<StoreNear_Info.DataBean> adapter;


    @Override
    public int getLayoutId() {
        return R.layout.activity_nearby;
    }

    @Override
    public void initView() {
        initToolbar();

    }

    private void initToolbar() {
        setBackArrow();
        setTitle("附近药店");
    }

    @Override
    public void initData() {
        initAdapter();
        setStoreNear(true);
    }


    private void initAdapter() {
        adapter = new BaseRecyclerAdapter<StoreNear_Info.DataBean>(Nearby_Activity.this, nearList, R.layout.adapter_item_nearby) {
            @Override
            public void convert(BaseRecyclerHolder holder, StoreNear_Info.DataBean item, int position, boolean isScrolling) {
                holder.setText(R.id.tv_name, item.getName());
                holder.setText(R.id.tv_address, item.getAddress());
                RatingBar rb_star = holder.getView(R.id.rb_star);
                float star = item.getStar();
                rb_star.setRating(star / 2);
                holder.setText(R.id.tv_star, star + "");
                int isself = item.getIsself();
                if (isself == 1) {
                    holder.getView(R.id.img_isself).setVisibility(View.VISIBLE);
                } else {
                    holder.getView(R.id.img_isself).setVisibility(View.GONE);

                }
                int invoice = item.getInvoice();
                if (invoice == 1) {
                    holder.getView(R.id.img_invoice).setVisibility(View.VISIBLE);
                } else {
                    holder.getView(R.id.img_invoice).setVisibility(View.GONE);

                }
                int type = item.getType();
                if (type == 1) {
                    holder.getView(R.id.img_type).setVisibility(View.VISIBLE);
                } else {
                    holder.getView(R.id.img_type).setVisibility(View.GONE);
                }
                holder.setText(R.id.tv_distant, item.getDistant() + "km");
                holder.setImageByUrl(R.id.b_picture, ApiService.BASE_URL + item.getPic());
            }
        };
        mNearbyRc.addItemDecoration(new CustomDecoration(Nearby_Activity.this, CustomDecoration.VERTICAL_LIST, R.drawable.divider_white_ef_1px, 12));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        mNearbyRc.setLayoutManager(linearLayoutManager);
        mNearbyRc.setAdapter(adapter);

        mNearbyRc.addOnScrollListener(new EndLessOnScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
//                if (pageIndex == currentPage) {
//                    return;
//                }
//                Logger.e("附近药店currentPage"+currentPage);
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        //请求网络
                        pageIndex++;
                        setStoreNear(false);

                    }
                }, 1000);
//                Logger.e("附近药店pageIndex"+pageIndex);
            }
        });
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                StoreNear_Info.DataBean dataBean = nearList.get(position);
                int id = dataBean.getId();
                String name = dataBean.getName();
                String pic = dataBean.getPic();
                String address = dataBean.getAddress();
                int star = dataBean.getStar();
                int isself = dataBean.getIsself();
                int invoice = dataBean.getInvoice();
                int type = dataBean.getType();
                String distant = dataBean.getDistant();
                Bundle bundle = new Bundle();
                bundle.putString("bean", (id + "," + name + "," + pic + "," + address + "," + star + "," + isself + "," + invoice + "," + type + "," + distant));
                startAct(PharmacyList_Activity.class, bundle);

            }
        });
    }

    /**
     *
     */
    private void setStoreNear(final boolean flag) {
        Map<String, String> map = new TreeMap<>();
        map.put("dis", 500000 + "");
        String jingdu = Hawk.get("经度");
        String weidu = Hawk.get("纬度");
        map.put("lat", String.valueOf(weidu));
        map.put("lon", String.valueOf(jingdu));
//        map.put("lon", String.valueOf(116.40311));
//        map.put("lat", String.valueOf(39.917548));
        map.put("num", 10 + "");
        map.put("page", pageIndex + "");
        map.put("sign", Md5Util2.createSign(map));

        RxUtils instance = RxUtils.getInstance();
        instance.retrofit.create(ApiService.class).postStornear(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<StoreNear_Info>() {

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
//                        ToastUtil.showShort(Nearby_Activity.this, "错误");
                    }

                    @Override
                    public void onNext(StoreNear_Info info) {
                        Logger.i("附近药店:" + info.toString());
                        if (info.getCode() == 1) {
                            if (flag) {
                                nearList.clear();
                            }
                            if (info.getData().size() > 0 && info.getData() != null) {
                                nearList.addAll(info.getData());
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }

                });
        try {
            //因为网络请求在子线程，所以不能让宿主线程过早的结束。
            Thread.sleep(100);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

    }


//    @OnClick(R.id.mNearby_xzadress)
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.mNearby_xzadress:
//                Intent intent = new Intent(Nearby_Activity.this, XzAdress_Activity.class);
//                startActivity(intent);
//                break;
//
//        }
//    }


}
